# coding=utf-8

from flask import render_template, flash, redirect, url_for, abort
from flask_login import login_user, current_user
from werkzeug.security import generate_password_hash
from ..forms import Userform, Registerform
from ..model import Users
from . import loginview

@loginview.route('/', methods=['GET', 'POST'])
def index():
    F = Userform()
    if F.validate_on_submit():
        U = Users.objects(name=F.name.data).first()
        if U is None:
            flash("The user does not exist.")
        else:
            if U.check_password(F.password.data):
                login_user(U)
                return redirect(url_for('TCview.index'))
            else:
                flash("Wrong password!")
    return render_template("login.html", F=F)

@loginview.route('/register', methods=['GET', 'POST'])
def register():
    F = Registerform()
    if F.validate_on_submit():
        u = Users(name=F.name.data, password_hash=generate_password_hash(F.password.data))
        u.save()
        flash("Register success!")
        return redirect(url_for('loginview.index'))
    return render_template("register.html", F=F)
